﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Lucene.Net;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Search.Highlight;
using Lucene.Net.Store;
using Lucene.Net.Index;
using System.Drawing;
using PanGu;
using PanGu.HighLight;
using Lucene.Net.Analysis.PanGu;
using System.Collections;
using System.IO;

public partial class product_input : System.Web.UI.Page
{
    protected ArrayList ItemList = new ArrayList();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["USERNAME"] == null)
        {
            Response.Redirect("error_log", true);
        }
        if (Session["IDENTITY"].Equals("employee") == true)
        {
            Response.Redirect("error_auth", true);
        }

        SqlConnection sc2 = new SqlConnection(ConfigurationManager.ConnectionStrings["wbkpt"].ConnectionString.ToString());
        sc2.Open();

        string enterid = Session["ENTERID"].ToString();

        SqlCommand com4 = new SqlCommand();
        com4.Connection = sc2;
        com4.CommandText = "select SORT_NAME from INFO_SORT where ENTER_ID=@idsort";
        com4.Parameters.AddWithValue("@idsort", enterid);
        SqlDataReader re = com4.ExecuteReader();
        while (re.Read())
        {
            ItemList.Add(re.GetString(re.GetOrdinal("SORT_NAME")));
        }
        dropdownlist1.DataBind();
        sc2.Close();

    }

    /// <summary>
    /// 文件上传函数
    /// </summary>
    /// <param name="path"></param>
    /// <param name="fileupload"></param>
    public bool upload(string path, System.Web.UI.WebControls.FileUpload fileupload, string product_id)
    {
        bool fileok = false;
        if (fileupload.HasFile)
        {
            string fileException = System.IO.Path.GetExtension(fileupload.FileName).ToLower();
            string[] allowedException = { ".jpg", ".bmp", ".gif" };
            for (int i = 0; i < allowedException.Length; i++)
            {
                if (fileException == allowedException[i])
                    fileok = true;
            }
        }
        if (fileok)
        {
            if (System.IO.Directory.Exists(path))
            {
            }
            else
            {
                System.IO.Directory.CreateDirectory(path);
            }

            fileupload.SaveAs(path + "\\" + product_id + "_" + "image_tmp" + ".jpg");
            return true;
        }
        else
        {
            Page.RegisterStartupScript("ss", "<script>alert('只能上传jpg,bmp,gif格式的图片文件！')</script>");
            return false;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {


        string Image_Path = "";
        if (img1.ImageUrl == "" || img1.ImageUrl == null)//如果没上传图片即count=0则跳出，count！=0继续
        {
            Page.RegisterStartupScript("ss", "<script>alert('请先上传封面图片！')</script>");
            return;
        }
        else
        {

            SqlConnection sc = new SqlConnection(ConfigurationManager.ConnectionStrings["wbkpt"].ConnectionString.ToString());
            sc.Open();
            SqlCommand com_check = new SqlCommand();
            com_check.Connection = sc;
            com_check.CommandText = "select PRODUCT_ID from INFO_PRODUCT where PRODUCT_NAME=@name";
            com_check.Parameters.AddWithValue("@name", TextBox1.Text);
            if (com_check.ExecuteScalar() != null)
            {
                Page.RegisterStartupScript("ss", "<script>alert('相同产品名称已存在，请试着更换产品名称或在产品名称前加上企业名称前缀。')</script>");
            }
            else//输入的产品名称是新的
            {
                //先生成新的ID，供上传图片文件时命名使用
                #region generate new id
                SqlCommand com1 = new SqlCommand();
                com1.Connection = sc;
                com1.CommandText = "select Max(PRODUCT_ID) from INFO_PRODUCT";
                while (Application["sqllock"] == "lock")
                {//检测是否已经锁住
                    System.Threading.Thread.Sleep(2000);
                }
                Application["sqllock"] = "lock";//上锁
                string max_id = "";
                try
                {
                    max_id = com1.ExecuteScalar().ToString();//获取数据库中最大ID
                }
                finally
                {
                    Application["sqllock"] = "unlock";//解锁
                }

                max_id = max_id.Remove(0, 1);
                int max_id1 = Convert.ToInt32(max_id) + 1;
                string new_id = "P" + max_id1.ToString();
                string ImagePath = "~/product_image/" + new_id + "_" + "image_tmp.jpg";
                string ImagePath2 = "~/product_image/" + new_id + "_" + "image.jpg";
                string ImagePath_tmp = Server.MapPath(ImagePath);
                string ImagePath_tmp2 = Server.MapPath(ImagePath2);
                #endregion
                if (File.Exists(ImagePath_tmp2) == true)
                    File.Delete(ImagePath_tmp2);
                File.Move(ImagePath_tmp, ImagePath_tmp2);
                File.Delete(ImagePath_tmp);

                string new_name = TextBox1.Text;
                int new_rates = Convert.ToInt32(TextBox3.Text);
                string sort = dropdownlist1.Text;
                string new_intro = "";

                //获取enter_id
                string enterid = Session["ENTERID"].ToString();

                SqlCommand com_convert = new SqlCommand();
                com_convert.Connection = sc;
                com_convert.CommandText = "insert into INFO_PRODUCT values (@id,@name,@image,@rates,@sort,@intro,@enterid,@spec)";
                com_convert.Parameters.AddWithValue("@id", new_id);
                com_convert.Parameters.AddWithValue("@name", new_name);
                //若之前有图片文件上传则将路径存入数据库，若没有则存入null

                Image_Path = "~/product_image/" + new_id + "_" + "image.jpg";
                com_convert.Parameters.AddWithValue("@image", Image_Path);
                com_convert.Parameters.AddWithValue("@rates", new_rates);
                com_convert.Parameters.AddWithValue("@sort", sort);
                com_convert.Parameters.AddWithValue("@intro", new_intro);
                com_convert.Parameters.AddWithValue("@enterid", enterid);
                com_convert.Parameters.AddWithValue("@spec", "FALSE");
                while (Application["sqllock"] == "lock")
                {//检测是否已经锁住
                    System.Threading.Thread.Sleep(2000);
                }
                Application["sqllock"] = "lock";//上锁        


                if (com_convert.ExecuteNonQuery() == 1)
                {
                    Application["sqllock"] = "unlock";//解锁
                    //更新进索引,企业索引目录在创建时就先生成索引文件
                    PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper(new WhitespaceAnalyzer());
                    analyzer.AddAnalyzer("name", new PanGuAnalyzer());
                    analyzer.AddAnalyzer("text", new PanGuAnalyzer());
                    IndexWriter writer = new IndexWriter(Server.MapPath("index/index_" + enterid), analyzer, false, IndexWriter.MaxFieldLength.LIMITED);
                    Document doc = new Document();
                    doc.Add(new Lucene.Net.Documents.Field("pid", "Identify " + new_id, Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.ANALYZED));
                    doc.Add(new Lucene.Net.Documents.Field("name", new_name, Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.ANALYZED));
                    doc.Add(new Lucene.Net.Documents.Field("text", new_intro, Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.ANALYZED));
                    writer.AddDocument(doc);
                    writer.Optimize();
                    writer.Close();

                    Page.RegisterStartupScript("ss", "<script>alert('成功提交产品信息!')</script>");
                    return;
                }
                else
                {
                    Application["sqllock"] = "unlock";//解锁 
                    Page.RegisterStartupScript("ss", "<script>alert('提交产品信息失败!')</script>");
                    return;
                }

            }
            sc.Close();
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        string FilePath = "";
        string ImagePath = "";

        SqlConnection sc = new SqlConnection(ConfigurationManager.ConnectionStrings["wbkpt"].ConnectionString.ToString());
        sc.Open();
        #region generate new id
        SqlCommand com1 = new SqlCommand();
        com1.Connection = sc;

        com1.CommandText = "select Max(PRODUCT_ID) from INFO_PRODUCT";
        while (Application["sqllock"] == "lock")
        {
            System.Threading.Thread.Sleep(2000);
        }
        Application["sqllock"] = "lock";


        string max_id = com1.ExecuteScalar().ToString();//获取数据库中最大ID
        Application["sqllock"] = "unlock";
        max_id = max_id.Remove(0, 1);
        int max_id1 = Convert.ToInt32(max_id) + 1;
        string new_id = "P" + max_id1.ToString();
        sc.Close();
        #endregion
        //上传图片文件，若不存在跳过
        if (this.FileUpload1.FileName != null && this.FileUpload1.FileName != "")
        {
            if (FileUpload1.PostedFile.ContentLength <= 0)
            {
                Page.RegisterStartupScript("ss", "<script>alert('上传图片文件为空，请重新选择文件!')</script>");
                return;
            }
            if (FileUpload1.HasFile)
            {
                if (FileUpload1.PostedFile.ContentLength > 4196304)
                {
                    Page.RegisterStartupScript("ss", "<script>alert('文件大小超过4M，请选择更小的图片上传!')</script>");
                    return;
                }
                else
                {
                    FilePath = Server.MapPath("~/product_image");
                }
                ImagePath = "~/product_image/" + new_id + "_" + "image" + "_tmp.jpg";
                //检验该count的tmp图片是否存在，若存在则删除后重新添加
                string ImagePath1 = Server.MapPath(ImagePath);
                if (File.Exists(ImagePath1))//先判断文件是否存在，若存在删除，不存在再执行操作
                    File.Delete(ImagePath1);

                if (upload(FilePath, this.FileUpload1, new_id) == true)
                {
                    img1.ImageUrl = ImagePath;
                    img1.Visible = true;
                    defaulttip.Visible = false;
                }


            }
            else
            {
                Page.RegisterStartupScript("ss", "<script>alert('所选路径不存在!')</script>");
                return;
            }
        }
    }
}